package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.CommentLikeApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.CommentLike;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private CommentLikeApi commentLikeApi;

    /**
     * 发布小视频
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }
        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }


    // 查询视频列表
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if(!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if( (page -1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e->Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findVideosByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length,pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if(list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if(info != null) {
                VideoVo vo = VideoVo.init(info, video);
                Boolean flag = videoApi.focus(video.getUserId(), UserHolder.getUserId());
                if (flag) {
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, vos);
    }

    // 视频关注
    public void userFocus(Long followUserId) {
        // 调用api查询是否已经关注
        Boolean focus = videoApi.focus(followUserId, UserHolder.getUserId());
        // 2. 如果已经关注,抛出异常
        if (focus) {
            throw new BusinessException(ErrorResult.loveError());
        }
        // 3. 调用api保存数据到MongoDB中
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        videoApi.saveFocus(focusUser);
        //4、拼接redis的key，将用户关注作者状态存入redis
        String key = Constants.USER_LIKE_KEY + followUserId;
        String hashKey = Constants.USER_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }


    // 视频取消关注
    public void disuserFocus(Long followUserId) {
        // 调用api查询是否已经关注
        Long userId = UserHolder.getUserId();
        Boolean focus = videoApi.focus(followUserId, userId);
        // 2. 如果未关注,抛出异常
        if (!focus) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        // 3. 调用api保存数据到MongoDB中
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        videoApi.deleteFocus(focusUser);
        //4、拼接redis的key，将用户关注作者状态存入redis
        String key = Constants.USER_LIKE_KEY + followUserId;
        String hashKey = Constants.USER_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    // 视频评论列表
    public PageResult findVideoComments(String videoId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findVideoComments(videoId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                Boolean hasLike = commentLikeApi.hasLike(comment.getId().toString(), UserHolder.getUserId());
                if(hasLike){
                    vo.setHasLiked(1);
                }
                vos.add(vo);

            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    // 发布评论
    public void saveComments(String videoId, String userComment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(userComment);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        commentApi.videoSave(comment);
    }

    /**
     * 视频评论点赞
     *
     * @param commentId
     */
    public void commentsLike(String commentId) {
        //1、调用API查询用户是否已点赞
        Boolean videoCommentLike = commentLikeApi.hasLike(commentId, UserHolder.getUserId());
        //2、如果已经点赞，抛出异常
        if (videoCommentLike) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、调用API保存数据到Mongodb
        CommentLike commentLike = new CommentLike();
        commentLike.setCommentId(commentId);
        commentLike.setUserId(UserHolder.getUserId());
        commentLike.setCreated(System.currentTimeMillis());
        commentLikeApi.save(commentLike);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.COMMENT_LIKE_KEY + commentId;
        String hashKey = Constants.COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    /**
     * 视频评论取消点赞
     * @param commentId
     */
    public void commentsDislike(String commentId) {
        //1、调用API查询用户是否已点赞
        Boolean videoCommentLike = commentLikeApi.hasLike(commentId, UserHolder.getUserId());
        //2、如果已经点赞，抛出异常
        if (!videoCommentLike) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API修改Mongodb数据
        CommentLike commentLike = new CommentLike();
        commentLike.setCommentId(commentId);
        commentLike.setUserId(UserHolder.getUserId());
        commentLike.setCreated(System.currentTimeMillis());
        commentLikeApi.delete(commentLike);
        //4、拼接redis的key，从redis删除用户状态
        String key = Constants.COMMENT_LIKE_KEY + commentId;
        String hashKey = Constants.COMMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
    }
}